package syan.sql.service.impl;

import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import syan.sql.Thread.ThreadPoolManager;
import syan.sql.mapper.RepairMapper;
import syan.sql.service.RepairService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author CHENTAIWEN
 * @create 2022/9/16 16:02
 */
@Slf4j
@Service
public class RepairServiceImpl extends Thread implements RepairService {


    @Autowired
    RepairMapper repairMapper;
    @Override
    public void update() {
        List<Map> pass=new ArrayList<>();
        List<Object> mistake = new ArrayList<>();
//        修复flow表
        List<Map<String, Object>> examineList = repairMapper.queryFlow();
        for (Map<String, Object> map : examineList){
            try {
                repairMapper.updateFlow(3,(Integer) map.get("sort"),(Integer) map.get("recordId"));
                pass.add(map);
            }catch (Exception e){
                mistake.add(map.get("recordId"));
            }
        }
        log.error("修复成功"+pass.size()+"条数据");
        log.error("修复错误数据List："+mistake);
    }

    public static final AtomicInteger complete = new AtomicInteger(0);
    public static final AtomicInteger Fail = new AtomicInteger(0);
    /**
     * 使用线程池操作修复
     */
    @Override
    public void repair(){

        List<Map<String, Object>> examineList = repairMapper.queryExamine();
        log.error("一共需要处理"+examineList.size()+"条信息");
        for (var examine : examineList) {
            try {
                ThreadPoolManager pool = ThreadPoolManager.getInstance();
                pool.AddMission(new RepairQuotation(examine));
            } catch (Exception e) {
                Fail.incrementAndGet();
                log.error("处理" + examine.get("quotation_num") + "出现问题");
                log.error(e.getMessage());
            }
        }
        ThreadPoolManager.getInstance().getPool().shutdown();
        while(true){
            if(ThreadPoolManager.getInstance().getPool().isTerminated()){
                break;
            }
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        log.error("成功修复了："+complete+"报价状态");
        log.error("未成功修复的报价状态："+Fail);
    }


}